package com.xjh.t.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjh.t.common.DataGridView;
import com.xjh.t.domain.GroupInfo;
import com.xjh.t.domain.Role;
import com.xjh.t.domain.UserInfo;
import com.xjh.t.service.IGroupInfoService;
import com.xjh.t.service.IUserInfoService;
import com.xjh.t.vo.RoleVo;
import com.xjh.t.vo.UserInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-03-12
 */
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IGroupInfoService groupInfoService;

    @RequestMapping("loadAllCustom")
    public DataGridView loadAllRole(UserInfoVo vo)
    {
        IPage<UserInfo> page = new Page<>(vo.getPage(),vo.getLimit());
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(vo.getUrName()),"ur_name",vo.getUrName());
        queryWrapper.like(StringUtils.isNotBlank(vo.getUrPhonenumber()),"ur_phonenumber",vo.getUrPhonenumber());

        List<Long> gpids = new ArrayList<>();
        if(StringUtils.isNotBlank(vo.getGroupName()))
            gpids = this.groupInfoService.queryGpIdsByGroupName("%"+vo.getGroupName()+"%");
        if(gpids.size() > 0)
        {
            queryWrapper.in(gpids.size() > 0,"gp_id",gpids);
        }

        queryWrapper.orderByDesc("ur_reg_date");
        this.userInfoService.page(page,queryWrapper);

        List<GroupInfo> groupInfos = this.groupInfoService.list();
        Map<Long,String> groupname = groupInfos.stream().collect(Collectors.toMap(GroupInfo::getGpId, GroupInfo::getGpName));
        List<UserInfo> list = page.getRecords();
        List<UserInfoVo> result = new ArrayList<>();
        for(UserInfo u1:list)
        {
            UserInfoVo userInfoVo = new UserInfoVo();
            BeanUtils.copyProperties(u1,userInfoVo);
            if(groupname.get(userInfoVo.getGpId().longValue()) != null)
                userInfoVo.setGroupName(groupname.get(userInfoVo.getGpId().longValue()));
            else
                userInfoVo.setGroupName("未加入公司");
            result.add(userInfoVo);
        }

        return new DataGridView(page.getTotal(),result);
    }

}



